<template>
  <BeModal class="source-table-modal" v-model:open="showModal" width="400px" :title="title" @ok="onOk" confirmText="保存">
    <div class="source-table-modal-body" v-if="showModal">
      <a-input class="search" @change="onSearch" v-model:value="keyword" placeholder="请输入名称">
        <template #suffix>
          <BeIcon icon="local:search" class="search-icon" />
        </template>
      </a-input>
      <div class="tree-wrap">
        <a-tree
          v-if="databaseTree.length"
          :expandedKeys="expandedKeys"
          :autoExpandParent="autoExpandParent"
          :checkedKeys="checkedKeys"
          blockNode
          checkable
          selectable
          :loadData="onLoadData"
          :treeData="databaseTree"
          @expand="onExpand"
          @select="onSelectDatabase"
          @check="onCheckDatabase"
        >
          <template #title="{ title }">
            <!-- prettier-ignore -->
            <span v-if="title.indexOf(keyword) > -1">{{ title.substring(0, title.indexOf(keyword)) }}<span style="color: #f50">{{ keyword }}</span>{{ title.substring(title.indexOf(keyword) + keyword.length) }}</span>
            <span v-else>{{ title }}</span>
          </template>
        </a-tree>
      </div>
    </div>
  </BeModal>
</template>
<script setup lang="ts">
import { dmsMaskCenterApi } from '@/api/dms-mask-center'
import BeIcon from '@/components/basics/BeIcon/src/BeIcon.vue'

interface Props {
  open?: boolean // 是否打开弹窗
  title?: string // 弹窗标题
  query?: any // 查询参数
  password?: string | null // 密码
  userName?: string | null // 用户名
}

// props
const props = withDefaults(defineProps<Props>(), {
  open: false,
  title: '',
  password: null,
  userName: null,
  query: [{ sourceflag: false, resourceId: '8bf745b306914364bc28f56f7dac4fd1', userName: null, password: null }]
})

// emits
const emit = defineEmits(['update:open', 'ok'])

// state
const showModal = ref(false) // 是否显示数据库选择弹窗
const expandedKeys = ref<string[]>([])
const autoExpandParent = ref(true)
const keyword = ref('') // 搜索关键字
const databaseTree = ref<any>([]) // 数据库树数据
const selectDatabaseItem = ref<any>(null) // 选中的数据库项
const checkedKeys = ref([]) // 选中的数据库项的 keys

// 清除数据
const reset = () => {
  keyword.value = ''
  databaseTree.value = []
  selectDatabaseItem.value = null
  expandedKeys.value = []
  checkedKeys.value = []
}

// 获取数据库组 树数据
const getdatabaseTree = async () => {
  const result = await dmsMaskCenterApi.getDatabaseList({ data: props.query })
  databaseTree.value = result.data || []
}

// 加载子节点
const onLoadData: any = async (treeNode: any) => {
  if (treeNode.dataRef.children) return
  const result = await dmsMaskCenterApi.getDatabaseList({
    data: [
      {
        dbName: treeNode.dataRef.dbName,
        resourceId: treeNode.dataRef.resourceId,
        sourceflag: !treeNode.dataRef.isLeaf,
        schemaName: treeNode.dataRef.schemaName || null,
        password: props.password,
        userName: props.userName
      }
    ]
  })
  treeNode.dataRef.children = result.data || []
  databaseTree.value = [...databaseTree.value]
  expandedKeys.value = [...expandedKeys.value, treeNode.key]
}

// 搜索函数：更新 expandedKeys
const onSearch = () => {
  const matchedKeys: string[] = []
  const loop = (data: any[]) => {
    for (const item of data) {
      if (item.title.toLowerCase().includes(keyword.value.toLowerCase())) {
        matchedKeys.push(item.key)
      }
      if (item.children) {
        loop(item.children)
      }
    }
  }
  loop(databaseTree.value)
  expandedKeys.value = matchedKeys
  autoExpandParent.value = true
}

const onExpand: any = (keys: string[]) => {
  expandedKeys.value = keys
  autoExpandParent.value = false
}

// 处理选择资产
const onSelectDatabase: any = (selectedKeys: any, e: any) => {
  selectDatabaseItem.value = e.node
  onLoadData(e.node)
}

// 处理选中数据库
const onCheckDatabase: any = async (_checkedKeys: any, e: any) => {
  if (!e.node.dataRef.children && !e.node.dataRef.isLeaf) await onLoadData(e.node, _checkedKeys)
  const isNotLeaf = !e.node.dataRef.isLeaf
  const childrenIsNotLeaf = (e.node.dataRef.children || []).every((child: any) => !child.isLeaf)
  if (isNotLeaf && childrenIsNotLeaf) {
    e.node.dataRef.disableCheckbox = true
    checkedKeys.value = _checkedKeys.filter((key: string) => key !== e.node.key)
  } else {
    checkedKeys.value = _checkedKeys
  }
}

// 处理显示
const handleOpen = () => {
  showModal.value = true
}

// 处理关闭
const handleClose = () => {
  showModal.value = false
}

// 处理确定按钮点击
const onOk = () => {
  emit('ok', { keys: checkedKeys.value })
}

// 初始化
const init = async () => {
  reset()
  await getdatabaseTree()
}

watch(
  () => props.open,
  (val) => {
    showModal.value = val
  }
)

watch(
  () => showModal.value,
  (val) => {
    emit('update:open', val)
    if (showModal.value) {
      init()
    }
  }
)

defineExpose({ open: handleOpen, close: handleClose })
</script>
<style lang="scss">
.source-table-modal {
  .ant-modal-body {
    height: calc(100vh - 321px);
    padding: 0;
  }
  &.be-modal--fullscreen {
    .ant-modal-body {
      height: calc(100vh - 121px);
    }
  }
  &-body {
    display: flex;
    flex-direction: column;
    height: 100%;
    padding: 10px;
    .search {
      width: 100%;
      margin-bottom: 10px;
      .search-icon {
        font-size: 18px;
        color: var(--muted-foreground);
      }
    }
    .tree-wrap {
      flex: 1;
      overflow: auto;
    }
  }
}
</style>
